package com.lilei.serialize;

import java.io.*;
import java.lang.reflect.Field;

/**
 * @Desc
 * @Auther 李雷(KyLin)
 * @Date 2020/03/31
 */
public class JavaSerializerWithFile implements ISerializer {


    @Override
    public <T> byte[] serialize(T obj) {
        try {
            Field field = obj.getClass().getDeclaredField("serialVersionUID");
            field.setAccessible(true);
            long serialVersionUID = (long) field.get(null);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(serialVersionUID + "_javafile_" + obj.getClass().getName())));
            objectOutputStream.writeObject(obj);
        } catch (IOException | NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {

        try {
            Field field = clazz.getDeclaredField("serialVersionUID");
            field.setAccessible(true);
            long serialVersionUID = (long) field.get(null);
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(serialVersionUID + "_javafile_" + clazz.getName())));
            return (T) objectInputStream.readObject();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }
}